package com.hhq.sso.auth.base.util;

import com.hhq.sso.auth.base.config.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * Description: some description
 * </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/6/20 11:04
 */
@Component
public class JwtUtils {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 生成令牌
     *
     * @param claims
     * @return
     */
    public String getJwt(Map<String, Object> claims) {

        String signingKey = jwtProperties.getSigningKey();
        long expire = jwtProperties.getExpire() * 1000;
        return Jwts.builder().setClaims(claims) // 设置载荷内容
            .signWith(SignatureAlgorithm.HS256, signingKey) // 设置签名算法
            .setExpiration(new Date(System.currentTimeMillis() + expire)) // 设置有效时间
            .compact();
    }

    /**
     * 解析令牌
     *
     * @param jwtString
     * @return
     */
    public Claims parseJwt(String jwtString) {
        String signingKey = jwtProperties.getSigningKey();
        return Jwts.parser().setSigningKey(signingKey) // 指定签名密钥
            .parseClaimsJws(jwtString) // 开始解析令牌
            .getBody();
    }
}
